package gorm

import (
	"database/sql/driver"
	"fmt"
	"time"
)

// DateTime datetime类型
type DateTime struct {
	time.Time
}

// MarshalJSON 数据序列化
func (t DateTime) MarshalJSON() ([]byte, error) {
	formatted := fmt.Sprintf("\"%s\"", t.Format(time.DateTime))
	return []byte(formatted), nil
}

// UnmarshalJSON json反序列表
func (t *DateTime) UnmarshalJSON(data []byte) error {
	tm, err := time.Parse(time.DateTime, string(data[1:len(data)-1]))
	if err != nil {
		return nil
	}
	*t = DateTime{Time: tm}
	return nil
}

// Value 返回datetime值
func (t DateTime) Value() (driver.Value, error) {
	var zeroTime time.Time
	if t.Time.UnixNano() == zeroTime.UnixNano() {
		return nil, nil
	}
	return t.Time, nil
}

// Scan 设置datetime值
func (t *DateTime) Scan(v interface{}) error {
	value, ok := v.(time.Time)
	if ok {
		*t = DateTime{Time: value}
		return nil
	}
	return fmt.Errorf("can not convert %v to timestamp", v)
}
